// import { showToast } from 'vant'
import { DriveCarListQuery, DriverCarVo, getDriveCarList } from '@/api/wuliu';
import { computed, ref, toRaw, type Ref } from 'vue';

export type DriveListQueryUpdater = (query: Ref<DriveCarListQuery>) => void | Promise<void>;

export function useDriveCarList(initListQuery: DriveCarListQuery = {}, immediate = true) {
  const listLoading = ref(false);

  const listRefreshing = ref(false);

  const listTotal = ref(0);

  const listQuery = ref<DriveCarListQuery>({
    isAsc: 'desc',
    pageNum: 1,
    pageSize: 10,
    ...initListQuery
  });
  const listData = ref<DriverCarVo[]>([]);

  const listLoadError = ref(false);

  const listLoaded = computed(() => {
    const { pageNum, pageSize } = listQuery.value;

    if (pageNum && pageSize) {
      return pageNum * pageSize >= listTotal.value;
    }

    return true;
  });

  const getListData = async () => {
    try {
      listLoading.value = true;
      listLoadError.value = false;

      const { rows, total } = await getDriveCarList(listQuery.value);
      listData.value = rows;
      listTotal.value = total;
    } catch (error) {
      listLoadError.value = true;
      console.error('Error get drive car list data', error);
    } finally {
      listLoading.value = false;
    }
  };

  const loadListData = async () => {
    try {
      listLoading.value = true;
      listLoadError.value = false;
      listQuery.value.pageNum!++;

      const res = await getDriveCarList(listQuery.value);
      const { rows, total } = res;

      listData.value = [...toRaw(listData.value), ...rows];
      listTotal.value = total;
    } catch (error) {
      listLoadError.value = true;
      console.error('Error get drive car list data', error);
    } finally {
      listLoading.value = false;
    }
  };

  const refreshListData = async () => {
    listRefreshing.value = true;
    listQuery.value.pageNum = 1;
    await getListData();
    listRefreshing.value = false;
  };

  const updateListQuery = async (updater: DriveListQueryUpdater) => {
    await updater(listQuery);
    await refreshListData();
  };

  if (immediate) {
    getListData();
  }

  return {
    listLoading,
    listRefreshing,
    listLoaded,
    listLoadError,
    listTotal,
    listQuery,
    listData,
    getListData,
    loadListData,
    refreshListData,
    updateListQuery
  };
}
